<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="重要级别" prop="level">
                <el-input v-model="queryParams.level" placeholder="请输入重要级别" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="chapterName">
                <el-input v-model="queryParams.chapterName" placeholder="请输入名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="笔记" prop="bookId" v-show="!lockBookId">
                <el-select v-model="queryParams.bookId" placeholder="请选择笔记" clearable size="small">
                    <el-option v-for="book in bookOptions" :key="book.id" :label="book.bookName" :value="book.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['note:chapter:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-tooltip class="item" effect="dark" content="锁定之后，只显示当前所属内容" placement="top">
                    <el-tag closable v-show="lockBookId" @close="unLockBook">
                        <i class="el-icon-lock"></i>锁定：{{lockBookName}}
                    </el-tag>
                </el-tooltip>

            </el-col>

            <el-col :span="1.5">
                <el-tooltip class="item" effect="dark" content="锁定之后，内容只显示当前所属内容" placement="top">
                    <el-tag closable v-show="lockChapterId" @close="unLock">
                        <i class="el-icon-lock"></i>锁定：{{lockChapterName}}
                    </el-tag>
                </el-tooltip>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="chapterList" row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column width="460" label="名称" align="center" prop="chapterName" />
            <el-table-column label="重要级别" align="center" prop="level" />
            <el-table-column label="页码" align="center" prop="page" />
            <el-table-column label="排序" align="center" prop="sort" />
            <!-- <el-table-column label="父节点" align="center" prop="parentId" /> -->
            <el-table-column label="笔记" align="center" prop="book.bookName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['note:chapter:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['note:chapter:remove']">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-lock" v-show="!lockChapterId" @click="doLock(scope.row)">锁定</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改章节管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">

                <el-form-item label="名称" prop="chapterName">
                    <el-input v-model="form.chapterName" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="页码" prop="page">
                    <el-input v-model="form.page" placeholder="请输入页码" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="父节点" prop="parentId">
                    <treeselect v-model="form.parentId" :options="chapterOptions" :normalizer="normalizer" placeholder="请选择父节点" />
                </el-form-item>
                <el-form-item label="笔记" prop="bookId" v-show="!lockBookId">
                    <el-select v-model="form.bookId" placeholder="请选择笔记" clearable size="small">
                        <el-option v-for="book in bookOptions" :key="book.id" :label="book.bookName" :value="book.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="重要级别" prop="level">
                    <el-input v-model="form.level" placeholder="请输入重要级别" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";

import { getAllBook } from "@/api/note/book";
import {
    listChapter,
    getChapter,
    delChapter,
    addChapter,
    updateChapter,
    exportChapter
} from "@/api/note/chapter";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "Chapter",
    components: {
        Treeselect
    },

    computed: {
        ...mapGetters({
            lockBookId: "bookId",
            lockBookName: "bookName",
            lockChapterId: "chapterId",
            lockChapterName: "chapterName"
        }),
        ...mapState(["refreshBook"])
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 章节管理表格数据
            chapterList: [],
            // 章节管理树选项
            chapterOptions: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                level: null,
                chapterName: null,
                parentId: null,
                bookId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            bookOptions: [],
            selections: []
        };
    },
    created() {
        this.getBookList();
        this.getList();
    },
    watch: {
        lockBookId: {
            handler: function(value) {
                this.queryParams.bookId = value;
                this.form.bookId = value;
                this.getList();
            },
            immediate: true
        },
        refreshBook: {
            handler: function(value) {
                if (value) {
                    this.getBookList();
                }
            },
            immediate: true
        }
    },
    methods: {
        unLockBook() {
            this.$store.dispatch("DoSetBook", null);
        },
        doLock(row) {
            console.info(row);
            this.$store.dispatch("DoSetBook", row.book).then(() => {
                this.$store.dispatch("DoSetChapter", row);
            });
        },
        unLock() {
            this.$store.dispatch("DoSetChapter", null);
        },
        getBookList() {
            getAllBook().then(response => {
                this.bookOptions = response.rows;
            });
        },
        /** 查询章节管理列表 */
        getList() {
            if (this.lockBookId) {
                this.queryParams.bookId = this.lockBookId;
            }
            this.loading = true;
            listChapter(this.queryParams).then(response => {
                this.chapterList = this.handleTree(
                    response.data,
                    "id",
                    "parentId"
                );
                this.loading = false;
            });
        },
        /** 转换章节管理数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.chapterName,
                children: node.children
            };
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            var param = {};
            if (this.lockBookId) {
                param.bookId = this.lockBookId;
            }
            listChapter(param).then(response => {
                this.chapterOptions = [];
                const data = { id: 0, name: "顶级节点", children: [] };
                data.children = this.handleTree(
                    response.data,
                    "id",
                    "parentId"
                );
                this.chapterOptions.push(data);
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                createTime: null,
                level: null,
                chapterName: null,
                page: null,
                sort: null,
                userId: null,
                parentId: null,
                bookId: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.getTreeselect();
            this.open = true;
            this.title = "添加章节管理";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.getTreeselect();
            if (row != null) {
                this.form.parentId = row.id;
            }
            getChapter(row.id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改章节管理";
            });
        },
        /** 提交按钮 */
        submitForm() {
            if (this.lockBookId) {
                this.form.bookId = this.lockBookId;
            }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateChapter(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                            this.$store.dispatch("DoRefreshChapter", true);
                        });
                    } else {
                        addChapter(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                            this.$store.dispatch("DoRefreshChapter", true);
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$confirm(
                '是否确认删除章节管理编号为"' + row.id + '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            )
                .then(function() {
                    return delChapter(row.id);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                });
        }
    }
};
</script>
